package com.zy.stock.controller;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.StockOperationRecord;
import com.zy.stock.domain.UserStockRl;
import com.zy.stock.dto.StockDto;
import com.zy.stock.service.StockOperationRecordService;
import com.zy.stock.service.StockService;

@Controller
public class StockController {
	
	private Logger logger = LoggerFactory.getLogger(StockController.class);
	
	@Autowired
	private StockService stockService;
	
	@Autowired
	private StockOperationRecordService stockOperationRecordService;
	
	@RequestMapping(value = "/stockManage")
	public ModelAndView toBillManager() {
		long start = System.currentTimeMillis();
		ModelAndView mav = new ModelAndView("stockManage");
		mav.addObject("menuid", 4);
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "getStockPage")
	public String getStockPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		String result = "";
		try {
			Integer draw = Integer.parseInt(request.getParameter("draw"));
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer length = Integer.parseInt(request.getParameter("length"));
			String stockName = request.getParameter("stockName");
			String stockCode = request.getParameter("stockCode");
			String orderColumn = request.getParameter("order[0][column]");
			String columnName = request.getParameter("columns[" + orderColumn + "][data]");
			String orderDir = request.getParameter("order[0][dir]");
			Pager<StockDto> pager = new Pager<>();
			StockDto dto = new StockDto();
			dto.setName(stockName);
			dto.setCode(stockCode);
			pager.setT(dto);
			pager.setPagenow(start / length + 1);
			pager.setSize(length);
			pager.setOrderCol(columnName);
			pager.setOrder(orderDir);
			Pager<List<Stock>> stations = stockService.findByCase(pager);
			map.put("data", stations.getT());
			map.put("recordsTotal", stations.getTotal());
			map.put("recordsFiltered", stations.getTotal());
			map.put("draw", draw);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping(value="toUploadStock") 
	public String toUpload(){
		return "stockUpload";
	}
	
	@RequestMapping(value="uploadStock") 
    public String upload(HttpServletRequest request, HttpServletResponse response){  
        MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;  
        MultipartFile file = mulRequest.getFile("file");  
        String filename = file.getOriginalFilename();  
        if (filename == null || "".equals(filename)){  
            return null;  
        }  
        try {  
            InputStream input = file.getInputStream();  
            XSSFWorkbook workBook = new XSSFWorkbook(input);
            XSSFSheet sheet = workBook.getSheetAt(0);  
            if (sheet != null){  
            	for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++){  
            		XSSFRow row = sheet.getRow(i);  
            		dealStockSave(row);//保存新增股票        		 
            	}  
            }  
//            sheet = workBook.getSheetAt(1);//处理16年股票
//            if (sheet != null){  
//            	for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++){  
//            		XSSFRow row = sheet.getRow(i);       		
//            		dealUserStockRlSave(row);
//            	}  
//            }  
            workBook.close(); 
        }catch (Exception e){  
        	e.printStackTrace();  
        } 
        return "redirect:stockManage";  
    }  
	
	private void dealUserStockRlSave(XSSFRow row){
		try {
			UserStockRl obj = new UserStockRl();
			//股票编码
			String name = row.getCell(0).getStringCellValue();
			Integer leftKH = name.indexOf("（");
			Integer rightKH = name.indexOf("）");
			logger.info(name);
			logger.info(leftKH.toString());
			logger.info(rightKH.toString());
			String code = name.substring(leftKH,rightKH);
			logger.info(code);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 处理股票导入
	 * @param row
	 * @param billTime
	 */
	private void dealStockSave(XSSFRow row){	
		try {
			//检查股票是否已经存在
			List<Stock> stocks = stockService.findByCode(row.getCell(1).toString());
			if(stocks!=null&&stocks.size()>0){
				logger.info(row.getCell(2).toString()+" 已经存在 不需要再次导入");
			}else{
				//保存股票
				Stock stock = new Stock();
				stock.setCreateTime(new Date());
				//状态
				stock.setStatus(row.getCell(0).toString());
				//股票代码
				stock.setCode(row.getCell(1).toString());
				//股票名称
				stock.setName(row.getCell(2).toString());
				//预测收益
				Cell earnings_cell =  row.getCell(3);
				earnings_cell.setCellType(Cell.CELL_TYPE_NUMERIC);
				Double earnings = earnings_cell.getNumericCellValue();
				stock.setEarnings(earnings);
				//估值
				Cell appraisement_cell =  row.getCell(4);
				appraisement_cell.setCellType(Cell.CELL_TYPE_NUMERIC);
				Double appraisement = appraisement_cell.getNumericCellValue();
				stock.setAppraisement(appraisement);
				
				//保存
				logger.info("保存股票..."+stock.getName());
				stockService.save(stock);
			}	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "getStockById")
	public String getStockById(HttpServletRequest request) {
		String result = "";
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			Stock entity = stockService.findById(id);
			map.put("data", entity);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "addStock")
	public Integer addStock(Stock stock, HttpServletRequest request) {
		try {
			stock.setCreateTime(new Date());
			stockService.save(stock);
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value = "updateStock")
	public Integer updateStock(Stock stock, HttpServletRequest request) {
		try {
			//记录变更日志
			stockOperationRecordService.save(buildRecord(stock));
			stockService.update(stock);
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
		return 0;
	}
	
	private StockOperationRecord buildRecord(Stock stock){
		StockOperationRecord record = new StockOperationRecord();
		String name = "修改股票:"+stock.getName()+"的数据";
		record.setName(name);
		StringBuffer sb = new StringBuffer();
		sb.append("估值为:");
		sb.append(stock.getAppraisement());
		sb.append(" 预测收益为:");
		sb.append(stock.getEarnings());	
		record.setDescription(sb.toString());
		record.setStockId(stock.getId());
		record.setCreateTime(new Date());
		record.setStockName(stock.getName());
		record.setStockCode(stock.getCode());
		return record;
	}
	
	@ResponseBody
	@RequestMapping(value = "deleteStockById")
	public Integer deleteStockById(HttpServletRequest request) {
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			stockService.deleteById(id);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
	}
	
	
}
